package com.tyao.note.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.tyao.framework.core.JsonResult;
import com.tyao.note.model.TSRole;
import com.tyao.note.model.TSUser;
import com.tyao.note.model.TULogin;
import com.tyao.note.service.UserService;
import com.tyao.note.service.exception.PasswordNotMatchException;
import com.tyao.note.service.exception.UserStatusException;
import com.tyao.note.service.exception.UsernameAlreadyExistException;

@Controller
public class UserController extends BaseController {
	@Autowired
	private UserService userService;

	/**
	 * 显示登录页面
	 * 
	 * @return 页面
	 */
	@RequestMapping("/note/login")
	public String showLogin() {
		return "/login";
	}

	@RequestMapping("/note/exit")
	public ModelAndView exit(HttpSession session) {
		// 销毁用户信息
		session.invalidate();
		return new ModelAndView("redirect:login");
	}

	/**
	 * 显示用户列表
	 * 
	 * @return
	 */
	@RequestMapping("/note/userList")
	public String userList(HttpServletRequest request) {
		List<TSUser> users = userService.getAllUser();
		request.setAttribute("users", users);
		return "/user-list";
	}

	/**
	 * 管理员添加用户
	 * 
	 * @return
	 */
	@RequestMapping("/note/userAdd")
	public String userAdd() {
		return "/user-add";
	}

	/**
	 * 用户修改密码页面
	 * 
	 * @return
	 */
	@RequestMapping("/note/pwdEdit")
	public String pwdEdit() {
		return "/pwd-edit";
	}

	/**
	 * 用户信息显示和修改页面
	 * 
	 * @return
	 */
	@RequestMapping("/note/userinfo")
	public String userinfo(Integer id, HttpServletRequest request) {
		TSUser tsUser = userService.getTsUserById(id);
		request.setAttribute("tsUser", tsUser);
		return "/userinfo";
	}

	/**
	 * 管理员变更员工密码页面
	 * 
	 * @return
	 */
	@RequestMapping("/note/changPwd")
	public String changPwd(Integer id, HttpServletRequest request) {
		TSUser userPwd = userService.getTsUserById(id);
		request.setAttribute("userPwd", userPwd);
		return "/chang-password";
	}

	/**
	 * 验证登录操作
	 * 
	 * @param username
	 * @param password
	 * @return
	 */
	@RequestMapping("/note/userLogin")
	@ResponseBody
	public JsonResult login(String username, String password, HttpSession session, HttpServletRequest request) {
		JsonResult jsonResult = new JsonResult();
		try {
			// 登录验证
			TSUser user = userService.login(username, password);
			// 获取用户角色信息
			TSRole tSRole = userService.getRoleByUserId(user.getId());
			// 设置到用户实体中
			user.setTsRole(tSRole);
			// 设置登陆信息
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			TULogin record = new TULogin();
			record.setUserId(user.getId());
			record.setLastLoginTime(sdf.parse(sdf.format(new Date())));
			String ip = request.getRemoteAddr();
			record.setLastLoginIp(ip);
			TULogin isFirstLogin = userService.loginInfo(user.getId());
			if (isFirstLogin == null) {
				record.setLoginNumber(1);
				userService.insertLoginInfo(record);
			} else {
				record.setLoginNumber(isFirstLogin.getLoginNumber() + 1);
				record.setId(isFirstLogin.getId());
				userService.updateLoginInfo(record);
			}
			jsonResult.setSuccess(true);
			jsonResult.setMsg("登录成功!");
			session.setAttribute("user", user);
		} catch (Exception e) {
			jsonResult.setSuccess(false);
			jsonResult.setMsg(e.getMessage());
		}
		return jsonResult;
	}

	/**
	 * 修改用户信息
	 * 
	 * @param gender
	 * @param phone
	 * @param email
	 * @param remark
	 *            备注信息
	 * @param session
	 * @return json对象
	 */
	@RequestMapping("/note/update")
	@ResponseBody
	public JsonResult updateUser(String gender, String phone, String email, String remark, Integer id,
			HttpSession session) {
		JsonResult jsonResult = new JsonResult();
		try {
			TSUser user = userService.updateUser(gender, phone, email, remark, id);
			jsonResult.setSuccess(true);
			jsonResult.setMsg("修改成功!");
			jsonResult.setData(user);
			session.setAttribute("user", user);
		} catch (Exception e) {
			jsonResult.setSuccess(false);
			jsonResult.setMsg(e.getMessage());
		}
		return jsonResult;
	}

	/**
	 * 修改密码操作
	 * 
	 * @param oldPwd
	 *            旧密码
	 * @param newPwd
	 *            新密码
	 * @param session
	 * @return
	 */
	@RequestMapping("/note/changePassword")
	@ResponseBody
	public JsonResult changePassword(String oldPwd, String newPwd, Integer id, HttpSession session) {
		JsonResult jsonResult = new JsonResult();
		try {
			if (id == null) {//用户修改密码
				userService.changePassword(oldPwd, newPwd, getId(session));
				session.invalidate();
			} else {//管理员修改用户密码
				userService.changePassword(oldPwd, newPwd, id);
			}
			jsonResult.setSuccess(true);
			jsonResult.setMsg("修改成功!");
		} catch (PasswordNotMatchException e) {
			jsonResult.setSuccess(false);
			jsonResult.setMsg(e.getMessage());
		}
		return jsonResult;
	}

	@RequestMapping("/note/addUser")
	@ResponseBody
	public JsonResult addUser(String username, String password, String gender, String phone, String email,
			String remark) {
		JsonResult jsonResult = new JsonResult();
		try {
			userService.addUser(username, password, gender, phone, email, remark);
			jsonResult.setSuccess(true);
			jsonResult.setMsg("添加成功!");
		} catch (UsernameAlreadyExistException e) {
			jsonResult.setSuccess(false);
			jsonResult.setMsg(e.getMessage());
		}
		return jsonResult;
	}

	@RequestMapping("/note/deleteBatch")
	@ResponseBody
	public JsonResult deleteBatch(Integer[] ids) {
		JsonResult jsonResult = new JsonResult();
		userService.deleteBatchById(ids);
		jsonResult.setSuccess(true);
		jsonResult.setMsg("批量删除成功!");
		return jsonResult;
	}

	@RequestMapping("/note/updateUserState")
	@ResponseBody
	public JsonResult updateUserState(Integer id) {
		JsonResult jsonResult = new JsonResult();
		try {
			userService.updateState(id);
			jsonResult.setSuccess(true);
			jsonResult.setMsg("修改状态成功!");
		} catch (Exception e) {
			jsonResult.setSuccess(false);
			jsonResult.setMsg(e.getMessage());
		}
		return jsonResult;
	}

	@RequestMapping("/note/searchUser")
	@ResponseBody
	public JsonResult searchUser(String datemin, String datemax, String search) {
		JsonResult jsonResult = new JsonResult();
		List<TSUser> searchUserResults = userService.searchByInputText(datemin, datemax, search);
		jsonResult.setSuccess(true);
		jsonResult.setMsg("搜索完成!");
		jsonResult.setData(searchUserResults);
		return jsonResult;
	}

	/**
	 * 重置密码
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/note/resetPassword")
	@ResponseBody
	public JsonResult resetPassword(Integer id) {
		JsonResult jsonResult = new JsonResult();
		try {
			// 更改成功
			if (userService.resetUserPassword(id)) {
				jsonResult.setSuccess(true);
				jsonResult.setMsg("密码已重置!");
			}
		} catch (UserStatusException e) {
			jsonResult.setSuccess(false);
			jsonResult.setMsg(e.getMessage());
		}
		return jsonResult;
	}

	/**
	 * 确认管理员密码
	 * 
	 * @param password
	 * @return
	 */
	@RequestMapping("/note/confirmAdminPassword")
	@ResponseBody
	public JsonResult confirmAdminPassword(String password) {
		JsonResult jsonResult = new JsonResult();
		try {
			if (userService.confirmAdminPassword(password)) {
				jsonResult.setSuccess(true);
				jsonResult.setMsg("管理员密码正确!");
			}
		} catch (PasswordNotMatchException e) {
			jsonResult.setSuccess(false);
			jsonResult.setMsg(e.getMessage());
		}
		return jsonResult;
	}
}
